package com.kakame.codenews.base.util;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.multipart.MultipartFile;
/**
 * UEditor文件上传辅助类
 *
 */
public class FileUtil {
    
    private static final String FILE_UPLOAD_PATH = File.separator + "upload"; 
	// 文件允许格式
	private static String[] allowFiles = { ".rar", ".doc", ".docx", ".zip", ".pdf",".txt", ".swf", ".wmv", ".gif", ".png", ".jpg", ".jpeg", ".bmp" };
	
	public static final HashMap<String, String> ERROR_INFO;

	static {
	    ERROR_INFO = new HashMap<String, String>();
	    ERROR_INFO.put("SUCCESS", "SUCCESS"); //默认成功
	    ERROR_INFO.put("NOFILE", "未包含文件上传域");
	    ERROR_INFO.put("TYPE", "不允许的文件格式");
	    ERROR_INFO.put("SIZE", "文件大小超出限制");
	    ERROR_INFO.put("ENTYPE", "请求类型ENTYPE错误");
	    ERROR_INFO.put("REQUEST", "上传请求异常");
	    ERROR_INFO.put("IO", "IO异常");
	    ERROR_INFO.put("DIR", "目录创建失败");
	    ERROR_INFO.put("UNKNOWN", "未知错误");
		
	}
	
	/**
	 * <pre>
	 * <b>desc:</b> 文件上传 
	 * <b>auth:</b> ex-hejm
	 * <b>date:</b> 2018年6月13日 下午5:20:55
	 * </pre>
	 * @param uploadFile
	 * @param request
	 * @param session
	 * @throws Exception
	 */
	public static List<Map<String, Object>> upload(MultipartFile[] uploadFile, HttpServletRequest request) {
	    String contextPath = request.getContextPath();
		String savePath = getFolder(request, FILE_UPLOAD_PATH);
		List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
		Map<String, Object> item = null;
		for (MultipartFile multipartFile : uploadFile) {
            if(multipartFile.getSize() > 0) {
                item = SystemUtil.getSOHashMap();
                String fileName = multipartFile.getOriginalFilename();
                String originalName = fileName.substring(fileName.lastIndexOf(System.getProperty("file.separator")) + 1);
                if (!checkFileType(originalName)) {
                    item.put("state", ERROR_INFO.get("TYPE"));
                } else {
                    item.put("state", ERROR_INFO.get("SUCCESS"));
                    item.put("originalName", originalName);
                    fileName = getName(originalName);
                    item.put("fileName", fileName);
                    String type = getFileExt(fileName);
                    item.put("type", type);
                    File file = new File(savePath, fileName);
                    item.put("size", file.length());
                    try {
                        multipartFile.transferTo(file);
                    } catch (IOException e) {
                        item.put("state", ERROR_INFO.get("IO"));
                    }
                    
                    item.put("url", contextPath + savePath.substring(savePath.lastIndexOf(FILE_UPLOAD_PATH)) + "/" + fileName);
                }
                list.add(item);
            }
        }
		return list;
	}

	/**
	 * 文件类型判断
	 * 
	 * @param fileName
	 * @return
	 */
	public static boolean checkFileType(String fileName) {
		Iterator<String> type = Arrays.asList(allowFiles).iterator();
		while (type.hasNext()) {
			String ext = type.next();
			if (fileName.toLowerCase().endsWith(ext)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 获取文件扩展名
	 * 
	 * @return string
	 */
	public static String getFileExt(String fileName) {
		return fileName.substring(fileName.lastIndexOf("."));
	}

	/**
	 * 依据原始文件名生成新文件名
	 * @return
	 */
	public static String getName(String fileName) {
		Random random = new Random();
		return random.nextInt(10000) + System.currentTimeMillis() + getFileExt(fileName);
	}

	/**
	 * 根据字符串创建本地目录 并按照日期建立子目录返回
	 * @param path 
	 * @return 
	 */
	public static String getFolder(HttpServletRequest request, String path) {
		SimpleDateFormat formater = new SimpleDateFormat("yyyyMMdd");
		String realPath = request.getServletContext().getRealPath(FILE_UPLOAD_PATH);
		realPath += "/" + formater.format(new Date());
		File dir = new File(realPath);
		if (!dir.exists()) {
			dir.mkdirs();
		}
		return realPath;
	}

}
